package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.GradeStudent;
import com.xmy.cultivate.entity.views.OrderDetailTiny;
import com.xmy.cultivate.entity.views.SelectStudent;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.IStudentGradeService;
import com.xmy.cultivate.service.IStudentSchoolService;
import com.xmy.cultivate.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.service.ITypeValueDataService;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Struct;
import java.util.*;

/**
 * <p>
 * 学生表 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-26
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Autowired
    IdWorker idWorker;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    DictMapper dictMapper;

    @Autowired
    @Lazy
    ITypeValueDataService iTypeValueDataService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;

    public IPage<Student> findAll(IPage<?> page, Wrapper wrapper){

        IPage<Student> studentIPage = studentMapper.findAll(page,wrapper);
        for (Student student:studentIPage.getRecords()){
            // as b where b.status <> 2 and b.residue_course_count>0 and b.student_id = a.id and a.deleted=0
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.ne("status",2);
            studentQueryWrapper.eq("deleted",0);
            studentQueryWrapper.gt("residue_course_count",0);
            studentQueryWrapper.eq("student_id",student.getId());
            Integer count = studentMapper.getApplyCourseCount(studentQueryWrapper);
            student.setApplyCourseCount(count);
        }

        return studentIPage;
    }

    public IPage<Student> rosterList(IPage<?> page, Wrapper wrapper){
        return studentMapper.rosterList(page,wrapper);
    }

    /**
     * 获取欠费
     * @param wrapper
     * @return
     */
    public BigDecimal arrearage(Wrapper wrapper){
        return studentMapper.arrearage(wrapper);
    }

    public IPage<Student> signUpStu(IPage<?> page, Wrapper wrapper){
        return this.signUpStu(page,wrapper);
    }

    public Student findOne(@Param("id") Long id){

        Student student = studentMapper.findOne(id);
        QueryWrapper<TypeValueData> typeValueDataQueryWrapper = new QueryWrapper<>();
        typeValueDataQueryWrapper.eq("for_id",student.getId());
        typeValueDataQueryWrapper.eq("type",4);
        List<TypeValueData> typeValueList = iTypeValueDataService.list(typeValueDataQueryWrapper);
        student.setLinkManList(typeValueList);
        return student;
    }

    public Boolean saveTo(Student student){
        student.setId(idWorker.nextId());

        List<TypeValueData> typeValueDataList = new ArrayList<>();

        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();
        Integer i = 0;
        while (iterator.hasNext()){
            TypeValueData typeValueData = iterator.next();
            if(typeValueData.getTypeId()!= null) {
                typeValueData.setForId(student.getId());
                typeValueData.setType(4);
                typeValueDataList.add(typeValueData);
                if(i==0){
                    QueryWrapper<Dict> queryWrapper =  new QueryWrapper<>();
                    queryWrapper.eq("num",typeValueData.getTypeId());
                    queryWrapper.eq("type",4);
                    Dict dict = dictMapper.selectOne(queryWrapper);
                    if(dict != null){
                        student.setLinkman(dict.getName());
                        student.setLinkmanPhone(typeValueData.getContent());
                    }
                }
                i++;
            }
        }

        if(typeValueDataList.size()>0){
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        studentMapper.insert(student);
        iStudentSchoolService.addOrUpdateData(student.getId(),student.getSchoolId());


        return true;
    }

    public boolean updateTo(Student student){
        List<TypeValueData> typeValueDataList = new ArrayList<>();
        List<TypeValueData> upTypeValueDataList = new ArrayList<>();
        Set<Long> atTypeValueData = new HashSet<>();

        Integer i = 0;
        Iterator<TypeValueData> iterator = student.getLinkManList().iterator();
        while (iterator.hasNext()){
            TypeValueData typeValueData = iterator.next();
            if(typeValueData.getTypeId()!=null) {
                if(typeValueData.getId()==0){
                    typeValueData.setId(idWorker.nextId());
                    typeValueData.setForId(student.getId());
                    typeValueData.setType(4);
                    typeValueDataList.add(typeValueData);
                }else{
                    typeValueData.setForId(student.getId());
                    typeValueData.setType(4);
                    upTypeValueDataList.add(typeValueData);
                    atTypeValueData.add(typeValueData.getId());
                }
                if(i==0){
                    QueryWrapper<Dict> queryWrapper =  new QueryWrapper<>();
                    queryWrapper.eq("num",typeValueData.getTypeId());
                    queryWrapper.eq("type",4);
                    Dict dict = dictMapper.selectOne(queryWrapper);
                    if(dict != null){
                        student.setLinkman(dict.getName());
                        student.setLinkmanPhone(typeValueData.getContent());
                    }
                }
                i++;
            }
        }

        //删除
        if(atTypeValueData.size()>0){
            QueryWrapper<TypeValueData> queryWrapper =  new QueryWrapper<>();
            queryWrapper.notIn("id",atTypeValueData);
            queryWrapper.eq("for_id",student.getId());
            iTypeValueDataService.remove(queryWrapper);
        }
        //新增
        if(typeValueDataList.size()>0){
            iTypeValueDataService.saveBatch(typeValueDataList);
        }
        //修改
        if(upTypeValueDataList.size()>0){
            iTypeValueDataService.updateBatchById(upTypeValueDataList,upTypeValueDataList.size());
        }

        //修改主体
        studentMapper.updateById(student);
        return true;
    }

    public IPage<Student> getStudentForGradeId(Long gradeId,String name,Integer pageNum,Integer pageSize){
        Grade grade = gradeMapper.selectById(gradeId);

        IPage<Student> iPage = new Page<>(pageNum,pageSize);

        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();

        //where id in (select b.student_id from student_grade as b where b.grade_id = #{gradeId} and b.status = 1 and deleted = 0 and reading_status<>3)
        studentGradeQueryWrapper.inSql("id","select b.student_id from student_grade as b where b.grade_id = "+gradeId+" and b.status = 1 and deleted = 0 and reading_status = 1");
        studentGradeQueryWrapper.like(StringUtils.isNotBlank(name),"name",name);


        IPage<Student> studentList = studentMapper.getStudentForGradeId(iPage,studentGradeQueryWrapper);
        for (Student student:studentList.getRecords()){
            OrderDetailTiny orderDetailTiny =  orderDetailMapper.getResidueCourseCountForCourseId(student.getId(),grade.getCourseId(),grade.getSchoolId());
            if(orderDetailTiny!=null){
                student.setUseCourseCount(orderDetailTiny.getUseCourseCount());
                student.setResidueCourseCount(orderDetailTiny.getResidueCourseCount());
            }else {
                student.setUseCourseCount(0);
                student.setUseCourseCount(0);
            }
            student.setClassId(gradeId);
        }
        return studentList;
    }

    public IPage<SelectStudent> getStudentForShift(IPage<?> page, Wrapper wrapper, Grade grade){

        IPage<SelectStudent> selectStudentIPage = studentMapper.getStudentForShift(page,wrapper,grade.getSchoolId(),grade.getCourseId());
        for (SelectStudent selectStudent:selectStudentIPage.getRecords()){
            selectStudent.setGradeId(grade.getId());
            //selectStudent.setHandleDate();
            selectStudent.setResidueCourseCount(orderDetailMapper.getResidueCourseHouseForCourseId(selectStudent.getStudentId(),grade.getCourseId(),grade.getSchoolId()));
        }

        return selectStudentIPage;
    }

    public boolean addGradeStudent(String gradeId,String[] studentList){

        Grade grade = gradeMapper.getOneForId(Long.parseLong(gradeId));
        if(grade==null){
            throw new CommonException(ResultCode.GRADE_NOT);
        }
        List<StudentGrade> studentGradeList = new ArrayList<>();
        for (String id:studentList){
            Long studentId = Long.parseLong(id);
            OrderDetail orderDetail = orderDetailMapper.getLastOneForCourseId(grade.getSchoolId(),studentId,grade.getCourseId());
            if(orderDetail != null){
                StudentGrade studentGrade = new StudentGrade();
                studentGrade.setOrderDetailId(orderDetail.getId());
                studentGrade.setStudentId(studentId);
                studentGrade.setSchoolId(grade.getSchoolId());
                studentGrade.setGradeId(grade.getId());
                studentGrade.setCourseId(grade.getCourseId());
                studentGrade.setSubjectsId(orderDetail.getSubjectsId());
                studentGrade.setRenewTeacherId(grade.getTeacherId());
                studentGrade.setYearPart(orderDetail.getYearPart());
                studentGrade.setQuarterNum(orderDetail.getQuarterNum());
                studentGrade.setSurplusCourseNum(orderDetail.getResidueCourseCount());
                studentGrade.setIsRenew(1);
                studentGradeList.add(studentGrade);
            }
        }
        if(studentGradeList.size()>0){
            iStudentGradeService.saveBatch(studentGradeList);
        }
        return true;
    }
}
